package com.health.article.controller;

import java.util.List;

import com.health.common.constant.CacheConstants;
import com.health.content.domain.ContentCategory;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.health.common.annotation.Log;
import com.health.common.core.controller.BaseController;
import com.health.common.core.domain.AjaxResult;
import com.health.common.enums.BusinessType;
import com.health.article.domain.ContentArticle;
import com.health.article.service.IContentArticleService;
import com.health.common.utils.poi.ExcelUtil;
import com.health.common.core.page.TableDataInfo;

/**
 * 资讯管理Controller
 * 
 * @author moxxie
 * @date 2025-10-31
 */
@RestController
@RequestMapping("/article/article")
public class ContentArticleController extends BaseController
{
    @Autowired
    private IContentArticleService contentArticleService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询资讯管理列表
     */
    @PreAuthorize("@ss.hasPermi('article:article:list')")
    @GetMapping("/list")
    public TableDataInfo list(ContentArticle contentArticle)
    {
        startPage();
        List<ContentArticle> list = contentArticleService.selectContentArticleList(contentArticle);
        return getDataTable(list);
    }

    /**
     * 导出资讯管理列表
     */
    @PreAuthorize("@ss.hasPermi('article:article:export')")
    @Log(title = "资讯管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ContentArticle contentArticle)
    {
        List<ContentArticle> list = contentArticleService.selectContentArticleList(contentArticle);
        ExcelUtil<ContentArticle> util = new ExcelUtil<ContentArticle>(ContentArticle.class);
        util.exportExcel(response, list, "资讯管理数据");
    }

    /**
     * 获取资讯管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('article:article:query')")
    @GetMapping(value = "/{articleId}")
    public AjaxResult getInfo(@PathVariable("articleId") Long articleId)
    {
        return success(contentArticleService.selectContentArticleByArticleId(articleId));
    }

    /**
     * 新增资讯管理
     */
    @PreAuthorize("@ss.hasPermi('article:article:add')")
    @Log(title = "资讯管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ContentArticle contentArticle)
    {
        redisTemplate.opsForSet().add(CacheConstants.TMP_VALID_FILE_SET, contentArticle.getCoverImage());
        return toAjax(contentArticleService.insertContentArticle(contentArticle));
    }

    /**
     * 修改资讯管理
     */
    @PreAuthorize("@ss.hasPermi('article:article:edit')")
    @Log(title = "资讯管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ContentArticle contentArticle)
    {
        redisTemplate.opsForSet().add(CacheConstants.TMP_VALID_FILE_SET, contentArticle.getCoverImage());
        // 新增资讯时状态默认为待审核(0)
        contentArticle.setStatus("0");
        return toAjax(contentArticleService.updateContentArticle(contentArticle));
    }

    /**
     * 删除资讯管理
     */
    @PreAuthorize("@ss.hasPermi('article:article:remove')")
    @Log(title = "资讯管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{articleIds}")
    public AjaxResult remove(@PathVariable Long[] articleIds)
    {
        return toAjax(contentArticleService.deleteContentArticleByArticleIds(articleIds));
    }

    /**
     * 查询所有栏目（用于下拉框）
     */
    @GetMapping("/categories")
    public AjaxResult getCategories()
    {
        List<ContentCategory> categories = contentArticleService.selectAllCategories();
        return success(categories);
    }

    /**
     * 置顶/取消置顶
     */
    @PreAuthorize("@ss.hasPermi('article:article:edit')")
    @Log(title = "资讯管理", businessType = BusinessType.UPDATE)
    @PutMapping("/toggleTop/{articleId}")
    public AjaxResult toggleTop(@PathVariable Long articleId)
    {
        ContentArticle article = contentArticleService.selectContentArticleByArticleId(articleId);
        if (article == null) {
            return error("资讯不存在");
        }
        // 切换置顶状态
        if ("1".equals(article.getIsTop())) {
            article.setIsTop("0");
        } else {
            article.setIsTop("1");
        }
        return toAjax(contentArticleService.updateContentArticle(article));
    }

    /**
     * 发布/下架操作
     */
    @PreAuthorize("@ss.hasPermi('article:article:edit')")
    @Log(title = "资讯管理", businessType = BusinessType.UPDATE)
    @PutMapping("/toggleStatus/{articleId}")
    public AjaxResult toggleStatus(@PathVariable Long articleId)
    {
        ContentArticle article = contentArticleService.selectContentArticleByArticleId(articleId);
        if (article == null) {
            return error("资讯不存在");
        }
        // 状态切换逻辑
        String currentStatus = article.getStatus();
        String newStatus;
        String message;

        switch (currentStatus) {
            case "0": // 待审核 -> 已发布
                newStatus = "1";
                message = "发布成功";
                break;
            case "1": // 已发布 -> 下架
                newStatus = "4";
                message = "下架成功";
                break;
            case "3": // 草稿 -> 待审核
                newStatus = "0";
                message = "提交审核成功";
                break;
            case "4": // 已下架 -> 待审核
                newStatus = "0";
                message = "重新提交成功";
                break;
            default:
                return error("当前状态不支持此操作");
        }
        article.setStatus(newStatus);
        boolean result = contentArticleService.updateContentArticle(article) > 0;
        return result ? success(message) : error("操作失败");
    }
}
